<?php
namespace Lib\Source\Driver\Zend;
use Lib\Data,
    Lib\Source\DriverAbstract;

class Cookie extends DriverAbstract{
    /**
     * @var Zend_Controller_Response_Http
     */
    protected $_response;
    
    /**
     * @var Data
     */
    protected $_storage;
    
    /**
     * @see Lib\Source.DriverAbstract::init()
     */
    public function init(){
        $front = \Zend_Controller_Front::getInstance();
        $this->_response = $front->getResponse();
    }
    
    /**
     * @see Lib\Source.DriverAbstract::load()
     */
    public function load($name, $default = null){
        if(isset($_COOKIE[$name])){
            $this->getStorage()->setValue($name, $_COOKIE[$name]);
            return true;
        } else{
            $this->getStorage()->setValue($name, $default);
            return false;
        }
    }
    
    
    /**
     *  @see Lib\Source.DriverAbstract::saveData()
     */
    public  function saveData($data){
        $result = false;
        foreach ($data as $name=>$value){
            if(is_array($value) || is_object($value)) continue; // Filter unneeded data from cookie
            $cookie = new \Zend_Http_Cookie($name, $value, $this->getOption('domain', '/'), $this->getOption('expires'), $this->getOption('path'));
            $this->_response->setHeader('Set-Cookie', $cookie->__toString());
            $result = true;
        }       
        return $result;
    }
}